package com.lagou.XMLtask;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

public class testbook {

    @Test
    public void test2() throws DocumentException {

        //1.获取解析XML的 SAXReader
        SAXReader reader = new SAXReader();

        //2.获取文档对象
        Document document = reader.read("E:\\LaGouTask\\Moudle2Task\\src\\com\\lagou\\XMLtask\\book.xml");

        //3.获取根节点
        Element rootElement = document.getRootElement();

        //4.获取子节点
        List<Element> elements = rootElement.elements();

        //5.获取集合中的第一个 子节点
        Element user = elements.get(0);

        //6.获取节点中的文本信息
        String id = user.attributeValue("id"); //获取属性id的值
        String name = user.elementText("name");
        String author = user.elementText("author");
        String price = user.elementText("price");
        String body = user.element("body").getText();
        //打印
        System.out.println("id：" + id + ",  书名：" + name + ",  作者：" + author + ",  价格：" + price + ",  " + body);

        //获取第二个子节点信息
        Element user1 = elements.get(1);
        String id1 = user1.attributeValue("id"); //获取属性id的值
        String name1 = user1.elementText("name");
        String author1 = user1.elementText("author");
        String price1 = user1.elementText("price");
        String body1 = user1.element("body").getText();
        //打印
        System.out.println("id：" + id1 + ",  书名：" + name1 + ",  作者：" + author1 + ",  价格：" + price1 + ",  " + body1);

        //获取第三个子节点信息
        Element user2 = elements.get(2);
        String id2 = user2.attributeValue("id"); //获取属性id的值
        String name2 = user2.elementText("name");
        String author2 = user2.elementText("author");
        String price2 = user2.elementText("price");
        String body2 = user2.element("body").getText();
        //打印
        System.out.println("id：" + id2 + ",  书名：" + name2 + ",  作者：" + author2 + ",  价格：" + price2 + ",  " + body2);

    }
}

